"use client";

import React, { useState, useEffect, useRef } from 'react';
import { useRouter, useParams } from 'next/navigation';
import { UUID, randString, removeArrayItem, isMobile } from '../utils/libs';
import { showMessageError, showLoading, closeLoading, showConfirm, showMessageSuccess } from '../utils/dialog';
import { PlusIcon, SearchIcon, MoreIcon, EditIcon, DeleteIcon, ShareIcon, InfoIcon, SendIcon, PauseIcon, MicIcon, AttachmentIcon, SettingsIcon, PlugIcon } from './Icons';
import Welcome from './Welcome';
import BackTop from './BackTop';
import ChatSetting from './ChatSetting';
import FileSelect from './FileSelect';
import FileList from './FileList';
import ChatPrompt from './ChatPrompt';
import ChatReply from './ChatReply';
import { getClientId, getSystemInfo } from '../utils/cache';
import { httpGet, httpPost, mockChatHistories } from '../utils/http';
import { useSharedStore } from '../utils/sharedata';
import Image from 'next/image';

// 导入 markdown-it
import MarkdownIt from 'markdown-it';

// 创建Markdown解析器
// @ts-ignore: markdown-it 类型定义问题
const md = new MarkdownIt({
  breaks: true,
  html: true,
  linkify: true,
  typographer: true,
});

// 添加类型定义
interface Role {
  id: number;
  name: string;
  icon: string;
  key: string;
  model_id: number;
  hello_msg: string;
}

interface Model {
  id: number;
  name: string;
  value: string;
  power: number;
}

interface ChatItem {
  chat_id: string;
  icon: string;
  role_id: number;
  model_id: number;
  title: string;
  edit: boolean;
  removing: boolean;
  pinned?: boolean;
}

interface Message {
  type: string;
  id: string;
  icon: string;
  content: string;
  prompt?: string;
  created_at?: number;
  tokens?: any;
  model?: string;
  role_id?: number;
  chat_id?: string;
}

interface File {
  url: string;
  name: string;
  size: number;
  type: string;
  [key: string]: any;
}

// 为Window添加clipboardData类型
declare global {
  interface Window {
    clipboardData: DataTransfer;
  }
}

export default function ChatPlus() {
  // 状态定义
  const [title, setTitle] = useState("GeekAI-智能助手");
  const [models, setModels] = useState<Model[]>([
    { id: 1, name: 'Deepseek-R1', value: 'deepseek-r1', power: 1 }
  ]);
  const [modelID, setModelID] = useState(1);
  const [chatData, setChatData] = useState<Message[]>([]);
  const [allChats, setAllChats] = useState<ChatItem[]>([]);
  const [chatList, setChatList] = useState<ChatItem[]>([]);
  const [mainWinHeight, setMainWinHeight] = useState(0);
  const [chatBoxHeight, setChatBoxHeight] = useState(0);
  const [leftBoxHeight, setLeftBoxHeight] = useState(0);
  const [loading, setLoading] = useState(false);
  const [roles, setRoles] = useState<Role[]>([
    { id: 1, name: '通用AI助手', icon: '', key: 'gpt', model_id: 0, hello_msg: '您好，我是您的AI助手，有什么可以帮助您的吗？' }
  ]);
  const router = useRouter();
  const params = useParams();
  const [roleId, setRoleId] = useState(1);
  const [chatId, setChatId] = useState("");
  const [newChatItem, setNewChatItem] = useState<ChatItem | null>(null);
  const [isLogin, setIsLogin] = useState(true);
  const [showHello, setShowHello] = useState(true);
  const inputRef = useRef<HTMLTextAreaElement>(null);
  const textHeightRef = useRef<HTMLDivElement>(null);
  const [showNotice, setShowNotice] = useState(false);
  const [notice, setNotice] = useState("");
  const noticeKey = "SYSTEM_NOTICE";
  const [row, setRow] = useState(4);
  const [showChatSetting, setShowChatSetting] = useState(false);
  const [listStyle, setListStyle] = useState("default");
  const [config, setConfig] = useState({ advance_voice_power: 0 });
  const [voiceChatUrl, setVoiceChatUrl] = useState("");
  const [tools, setTools] = useState<any[]>([]);
  const [toolSelected, setToolSelected] = useState<string[]>([]);
  const [stream, setStream] = useState(true);
  const [prompt, setPrompt] = useState("");
  const [showStopGenerate, setShowStopGenerate] = useState(false);
  const [lineBuffer, setLineBuffer] = useState("");
  const [canSend, setCanSend] = useState(true);
  const [isNewMsg, setIsNewMsg] = useState(true);
  const [disableModel, setDisableModel] = useState(false);
  const [tmpChatTitle, setTmpChatTitle] = useState("");
  const [chatName, setChatName] = useState("");
  const [files, setFiles] = useState<File[]>([]);
  const [showConversationDialog, setShowConversationDialog] = useState(false);
  const [frameLoaded, setFrameLoaded] = useState(false);
  const store = useSharedStore();
  const [isAsideCollapsed, setIsAsideCollapsed] = useState(false);
  const [isHeaderMenuOpen, setIsHeaderMenuOpen] = useState(false);
  const [isEditingTitle, setIsEditingTitle] = useState(false);

  // 工具函数
  const resizeElement = () => {
    setChatBoxHeight(window.innerHeight - 101 - 82 - 38);
    setMainWinHeight(window.innerHeight - 59);
    setLeftBoxHeight(window.innerHeight - 90 - 100);
  };

  const getRoleById = (rid: number): Role | null => {
    for (let i = 0; i < roles.length; i++) {
      if (roles[i].id === rid) {
        return roles[i];
      }
    }
    return null;
  };

  const getModelValue = (model_id: number): string => {
    for (let i = 0; i < models.length; i++) {
      if (models[i].id === model_id) {
        return models[i].value;
      }
    }
    return "";
  };

  const disableInput = (force: boolean) => {
    setCanSend(false);
    setShowStopGenerate(!force);
  };

  const enableInput = () => {
    setCanSend(true);
    setShowStopGenerate(false);
  };

  // 发送模拟消息
  const sendMockMessage = (content: string) => {
    const newPrompt = {
      type: "prompt" as const,
      id: randString(32),
      icon: '/images/user.png',
      content: content,
      model: getModelValue(modelID),
      created_at: new Date().getTime() / 1000,
    };
    
    const newChatData = [...chatData, newPrompt];
    setChatData(newChatData);

    setTimeout(() => {
      const chatBox = document.getElementById("chat-box");
      if (chatBox) {
        chatBox.scrollTo(0, chatBox.scrollHeight);
      }
    }, 100);

    setShowHello(false);
    disableInput(false);
    
    // --- MOCK WEBSOCKET RESPONSE ---
    const mockReply = "这是一个模拟的回复。我将逐字显示以模拟打字机效果。";
    let currentReply = "";
    
    const chatRole = getRoleById(roleId);
    const replyMessage = {
      type: "reply" as const,
      id: randString(32),
      icon: '/images/AI.png',
      prompt: content,
      content: "",
    };

    const initialChatData = [...newChatData, replyMessage];
    setChatData(initialChatData);

    const typeEffect = setInterval(() => {
      if (currentReply.length < mockReply.length) {
        currentReply += mockReply[currentReply.length];
      
        setChatData(prevChatData => {
          const updatedChatData = [...prevChatData];
          const lastMessage = updatedChatData[updatedChatData.length - 1];
          if (lastMessage && lastMessage.type === 'reply') {
            lastMessage.content = currentReply;
          }
          return updatedChatData;
        });

        setTimeout(() => {
          const chatBox = document.getElementById("chat-box");
          if (chatBox) {
            chatBox.scrollTo(0, chatBox.scrollHeight);
          }
        }, 0);
      } else {
        clearInterval(typeEffect);
        enableInput();

        if (newChatItem !== null) {
            const updatedItem = {...newChatItem};
            updatedItem.title = tmpChatTitle || content.substring(0, 20);
            updatedItem.chat_id = chatId;
            
            if (!mockChatHistories[chatId as keyof typeof mockChatHistories]) {
                 mockChatHistories[chatId as keyof typeof mockChatHistories] = [];
            }
             mockChatHistories[chatId as keyof typeof mockChatHistories].push({ type: 'prompt', id: randString(32), icon: '', content: content});
             mockChatHistories[chatId as keyof typeof mockChatHistories].push({ type: 'reply', id: randString(32), icon: '', content: currentReply});


            setChatList([updatedItem, ...chatList]);
            setAllChats([updatedItem, ...allChats]);
            setNewChatItem(null);
        }
      }
    }, 50);
    // --- END MOCK WEBSOCKET RESPONSE ---
    
    setTmpChatTitle(content);
  };

  // 初始化数据
  const initData = () => {
    // 加载模型
    httpGet("/api/model/list")
      .then((res: any) => {
        setModels(res.data);
        if (!modelID) {
          setModelID(res.data[0].id);
        }
        // 加载角色列表
        httpGet(`/api/app/list/user`, { id: roleId })
          .then((res: any) => {
            setRoles(res.data);
            if (!roleId) {
              setRoleId(res.data[0].id);
            }
            // 移除登录检查，直接创建新对话
            newChat();
          })
          .catch((e: any) => {
            showMessageError("获取聊天角色失败: " + e.message);
          });
      })
      .catch((e: any) => {
        showMessageError("加载模型失败: " + e.message);
      });

    // 获取会话列表
    httpGet("/console/api/installed-apps/b2652e18-08fa-4984-929b-30ded66c3b88/conversations?limit=100&pinned=false")
      .then((res: any) => {
        if (res.data) {
          setChatList([{chat_id: 'test', icon:'/images/AI.png',role_id:1,model_id:1, title:'你好', edit:false,removing:false, pinned: false}]);
          setAllChats([{chat_id: 'test', icon:'/images/AI.png',role_id:1,model_id:1, title:'你好', edit:false,removing:false, pinned: false}]);
        }
      })
      .catch(() => {
        showMessageError("加载会话列表失败！");
      });

    // 允许在输入框粘贴文件
    if (inputRef.current) {
      inputRef.current.addEventListener("paste", (event: ClipboardEvent) => {
        const items = (event.clipboardData || window.clipboardData).items;
        for (let i = 0; i < items.length; i++) {
          const item = items[i];
          if (item.kind === "file") {
            const file = item.getAsFile();
            if (file) {
              const formData = new FormData();
              formData.append("file", file);
              setLoading(true);
              // 执行上传操作
              httpPost("/api/upload", formData)
                .then((res: any) => {
                  setFiles([...files, res.data]);
                  showMessageSuccess("上传成功");
                  setLoading(false);
                })
                .catch((e: any) => {
                  showMessageError("文件上传失败:" + e.message);
                  setLoading(false);
                });
              break;
            }
          }
        }
      });
    }
  };

  // 创建新聊天
  const _newChat = () => {
    const newChatId = UUID();
    router.push(`/chatTest/${newChatId}`);
  };

  const newChat = () => {
    const role = getRoleById(roleId);
    if (role) {
      setShowHello(role.key === "gpt");
      // if the role bind a model, disable model change
      setDisableModel(false);
      if (role.model_id > 0) {
        setModelID(role.model_id);
        setDisableModel(true);
      }
    }
    
    // 已有新开的会话
    if (newChatItem !== null && newChatItem.role_id === roleId) {
      return;
    }

    // 获取当前聊天角色图标
    let icon = "";
    roles.forEach((item) => {
      if (item.id === roleId) {
        icon = item.icon;
      }
    });
    
    const newId = (params.chatId || UUID()) as string;
    setChatId(newId);

    setNewChatItem({
      chat_id: "",
      icon: '/images/AI.png',
      role_id: roleId,
      model_id: modelID,
      title: "",
      edit: false,
      removing: false,
    });
    
    setShowStopGenerate(false);
    loadChatHistory(newId);
    if (!params.chatId) {
      router.push(`/chatTest/${newId}`);
    }
  };

  // 加载聊天历史
  const loadChatHistory = (chatId: string) => {
    setChatData([]);
    setLoading(true);
    httpGet("/api/chat/history?chat_id=" + chatId)
      .then((res: any) => {
        setLoading(false);
        const data = res.data;
        if ((!data || data.length === 0) && chatData.length === 0) {
          // 加载打招呼信息
          const _role = getRoleById(roleId);
          if (_role) {
            setChatData([{
              chat_id: chatId,
              role_id: roleId,
              type: "reply",
              id: randString(32),
              icon: '/images/AI.png',
              content: _role.hello_msg,
            }]);
          }
          return;
        }
        setShowHello(false);
        const newChatData = [];
        for (let i = 0; i < data.length; i++) {
          const message = { ...data[i] };
          if (message.type === 'prompt') {
            message.icon = '/images/user.png';
          } else if (message.type === 'reply') {
            message.icon = '/images/AI.png';
          }

          if (message.type === "reply" && i > 0) {
            message.prompt = data[i - 1].content;
          }
          newChatData.push(message);
        }
        setChatData(newChatData);

        setTimeout(() => {
          const chatBox = document.getElementById("chat-box");
          if (chatBox) {
            chatBox.scrollTo(0, chatBox.scrollHeight);
          }
        }, 100);
      })
      .catch((e: any) => {
        // TODO: 显示重新加载按钮
        showMessageError("加载聊天记录失败：" + e.message);
      });
  };

  // 切换会话
  const loadChat = (chat: ChatItem) => {
    if (chatId === chat.chat_id) {
      return;
    }
    router.push(`/chatTest/${chat.chat_id}`);
  };

  // 发送消息
  const sendMessage = (messageText?: string) => {
    if (canSend === false) {
      showMessageError("AI 正在作答中，请稍后...");
      return;
    }
    
    const content = messageText ?? prompt;
    if (content.trim().length === 0) {
      showMessageError("请输入要发送的消息！");
      return false;
    }
    
    // 如果携带了文件，则串上文件地址
    let contentWithFiles = content;
    if (files.length === 1) {
      contentWithFiles += files.map((file) => file.url).join(" ");
    } else if (files.length > 1) {
      showMessageError("当前只支持上传一个文件！");
      return false;
    }
    
    sendMockMessage(contentWithFiles);
    
    setPrompt("");
    setFiles([]);
    setRow(4);
    return true;
  };

  // 输入处理函数
  const onInput = (e: React.KeyboardEvent<HTMLTextAreaElement> | React.ChangeEvent<HTMLTextAreaElement>) => {
    // 根据输入的内容自动计算输入框的行数
    if (inputRef.current && textHeightRef.current) {
      const lineHeight = parseFloat(window.getComputedStyle(inputRef.current).lineHeight);
      textHeightRef.current.style.width = inputRef.current.clientWidth + "px"; // 设定宽度和 textarea 相同
      const lines = Math.floor(textHeightRef.current.clientHeight / lineHeight);
      inputRef.current.scrollTo(0, inputRef.current.scrollHeight);
      
      const minRows = 4;
      const maxRows = 10;

      if (lines <= minRows) {
        setRow(minRows);
      } else if (lines <= maxRows) {
        setRow(lines);
      } else {
        setRow(maxRows);
      }
    }

    // 输入回车自动提交
    if ('keyCode' in e && e.keyCode === 13) {
      if (e.ctrlKey) {
        // Ctrl + Enter 换行
        setPrompt(prompt + "\n");
        return;
      }
      e.preventDefault();
      sendMessage();
    }
  };

  // 在组件挂载时初始化
  useEffect(() => {
    if (isMobile()) {
      router.push("/mobile/chatTest");
      return;
    }

    if (params.chatId && params.chatId !== chatId) {
        setChatId(params.chatId as string);
    }

    resizeElement();
    initData();

    // 获取系统配置
    getSystemInfo()
      .then((res: any) => {
        setConfig(res.data);
        setTitle(res.data.title);
      })
      .catch((e: any) => {
        console.error("获取系统配置失败：" + e.message);
      });

    // 获取系统公告
    httpGet("/api/config/get?key=notice")
      .then((res: any) => {
        try {
          const noticeContent = md.render(res.data.content);
          setNotice(noticeContent);
          const oldNotice = localStorage.getItem(noticeKey);
          // 如果公告有更新，则显示公告
          if (oldNotice !== noticeContent && noticeContent.length > 10) {
            setShowNotice(true);
          }
        } catch (e) {
          console.warn(e);
        }
      })
      .catch((e: any) => {
        console.error("获取系统配置失败：" + e.message);
      });

    // 获取工具函数
    httpGet("/api/function/list")
      .then((res: any) => {
        setTools(res.data);
      })
      .catch((e: any) => {
        showMessageError("获取工具函数失败：" + e.message);
      });

    // 处理窗口大小变化
    window.onresize = resizeElement;

    // 添加消息处理器
    store.addMessageHandler("chat", (data: any) => {
      // 丢去非本频道和本客户端的消息
      if (data.channel !== "chat" || data.clientId !== getClientId()) {
        return;
      }

      if (data.type === "error") {
        showMessageError(data.body);
        return;
      }

      const chatRole = getRoleById(roleId);
      if (isNewMsg && data.type !== "end") {
        const prePrompt = chatData[chatData.length - 1]?.content;
        const newData = [...chatData, {
          type: "reply",
          id: randString(32),
          icon: '/images/AI.png',
          prompt: prePrompt,
          content: data.body,
        }];
        setChatData(newData);
        setIsNewMsg(false);
        setLineBuffer(data.body);
      } else if (data.type === "end") {
        // 消息接收完毕
        // 追加当前会话到会话列表
        if (newChatItem !== null) {
          const updatedItem = {...newChatItem};
          updatedItem.title = tmpChatTitle;
          updatedItem.chat_id = chatId;
          setChatList([updatedItem, ...chatList]);
          setNewChatItem(null); // 只追加一次
        }

        enableInput();
        setLineBuffer(""); // 清空缓冲

        // 获取 token
        const reply = chatData[chatData.length - 1];
        httpPost("/api/chat/tokens", {
          text: "",
          model: getModelValue(modelID),
          chat_id: chatId,
        })
          .then((res: any) => {
            const updatedChatData = [...chatData];
            const lastIndex = updatedChatData.length - 1;
            if (lastIndex >= 0) {
              updatedChatData[lastIndex] = {
                ...updatedChatData[lastIndex],
                created_at: new Date().getTime(),
                tokens: res.data
              };
              setChatData(updatedChatData);
            }
            
            // 将聊天框的滚动条滑动到最底部
            setTimeout(() => {
              const chatBox = document.getElementById("chat-box");
              if (chatBox) {
                chatBox.scrollTo(0, chatBox.scrollHeight);
              }
            }, 100);
          })
          .catch(() => {});
        setIsNewMsg(true);
      } else if (data.type === "text") {
        const updatedBuffer = lineBuffer + data.body;
        setLineBuffer(updatedBuffer);
        
        const updatedChatData = [...chatData];
        const reply = updatedChatData[updatedChatData.length - 1];
        if (reply) {
          reply.content = updatedBuffer;
          setChatData(updatedChatData);
        }
      }
      
      // 将聊天框的滚动条滑动到最底部
      setTimeout(() => {
        const chatBox = document.getElementById("chat-box");
        if (chatBox) {
          chatBox.scrollTo(0, chatBox.scrollHeight);
        }
      }, 100);
    });

    return () => {
      // 清理工作
      window.onresize = null;
      store.removeMessageHandler("chat");
    };
  }, []);

  // 自动填充prompt
  const autofillPrompt = (text: string) => {
    setPrompt(text);
    if (inputRef.current) {
      inputRef.current.focus();
    }
    sendMessage(text);
  };

  // 编辑会话标题
  const editChatTitle = (chat: ChatItem) => {
    const updatedList = chatList.map(item => {
      if (item.chat_id === chat.chat_id) {
        return { ...item, edit: true };
      }
      return item;
    });
    setChatList(updatedList);
    setTmpChatTitle(chat.title);
    setTimeout(() => {
      const element = document.getElementById("chat-" + chat.chat_id);
      if (element) {
        element.focus();
      }
    }, 100);
  };

  // 处理标题编辑时的按键
  const titleKeydown = (e: React.KeyboardEvent, chat: ChatItem) => {
    if (e.key === 'Enter') {
      e.stopPropagation();
      editConfirm(chat);
    }
  };

  // 阻止事件冒泡
  const stopPropagation = (e: React.MouseEvent) => {
    e.stopPropagation();
  };

  // 确认编辑
  const editConfirm = (chat: ChatItem) => {
    if (tmpChatTitle === "") {
      showMessageError("请输入会话标题！");
      return;
    }
    if (!chat.chat_id) {
      showMessageError("对话 ID 为空，请刷新页面再试！");
      return;
    }
    if (tmpChatTitle === chat.title) {
      const updatedList = chatList.map(item => {
        if (item.chat_id === chat.chat_id) {
          return { ...item, edit: false };
        }
        return item;
      });
      setChatList(updatedList);
      return;
    }

    httpPost("/api/chat/update", {
      chat_id: chat.chat_id,
      title: tmpChatTitle,
    })
      .then(() => {
        const updatedList = chatList.map(item => {
          if (item.chat_id === chat.chat_id) {
            return { ...item, title: tmpChatTitle, edit: false };
          }
          return item;
        });
        setChatList(updatedList);
      })
      .catch((e: any) => {
        showMessageError("操作失败：" + e.message);
      });
  };

  // 删除会话
  const removeChat = (chat: ChatItem) => {
    showConfirm(`该操作会删除"${chat.title}"`, () => {
      httpGet("/api/chat/remove?chat_id=" + chat.chat_id)
        .then(() => {
          const newChatList = chatList.filter(item => item.chat_id !== chat.chat_id);
          setChatList(newChatList);
          // 重置会话
          _newChat();
        })
        .catch((e: any) => {
          showMessageError("操作失败：" + e.message);
        });
    });
  };

  // 搜索会话
  const searchChat = (e: React.KeyboardEvent) => {
    if (chatName === "") {
      setChatList(allChats);
      return;
    }
    if (e.key === 'Enter') {
      const items = allChats.filter(chat => 
        chat.title.toLowerCase().includes(chatName.toLowerCase())
      );
      setChatList(items);
    }
  };

  // 分享会话
  const shareChat = (chat: ChatItem) => {
    if (!chat.chat_id) {
      showMessageError("请先选中一个会话");
      return;
    }

    // if (typeof window !== 'undefined') {
    //   const url = window.location.protocol + "//" + window.location.host + "/chatTest/export?chat_id=" + chat.chat_id;
    //   window.open(url, "_blank");
    // }
  };

  // 清除所有会话
  const clearAllChats = () => {
    showConfirm("清除所有对话?此操作不可撤销！", () => {
      httpGet("/api/chat/clear")
        .then(() => {
          showMessageSuccess("操作成功！");
          setChatData([]);
          setChatList([]);
          newChat();
        })
        .catch((e: any) => {
          showMessageError("操作失败：" + e.message);
        });
    }, { confirmText: '删除对话', title: '警告' });
  };

  // 停止生成
  const stopGenerate = () => {
    setShowStopGenerate(false);
    httpGet("/api/chat/stop?session_id=" + getClientId()).then(() => {
      enableInput();
    });
  };

  // 重新生成
  const reGenerate = (prompt_to_regen: string) => {
    disableInput(false);
    const text = "重新回答下述问题：" + prompt_to_regen;
    sendMockMessage(text);
  };

  // 实时语音对话
  const realtimeChat = () => {
    showLoading("正在连接...");
    httpPost("/api/realtime/voice")
      .then((res: any) => {
        setVoiceChatUrl(res.data);
        setShowConversationDialog(true);
        closeLoading();
      })
      .catch((e: any) => {
        showMessageError("连接失败：" + e.message);
        closeLoading();
      });
  };

  // 插入文件
  const insertFile = (file: File) => {
    setFiles([...files, file]);
  };

  // 移除文件
  const removeFile = (file: File) => {
    setFiles(files.filter(f => f.url !== file.url));
  };

  // 不再显示公告
  const notShow = () => {
    localStorage.setItem(noticeKey, notice);
    setShowNotice(false);
  };

  // 置顶会话
  const pinChat = (chatToPin: ChatItem) => {
    const updatedChats = allChats.map(chat =>
      chat.chat_id === chatToPin.chat_id ? { ...chat, pinned: !chat.pinned } : chat
    );

    updatedChats.sort((a, b) => {
      if (a.pinned && !b.pinned) return -1;
      if (!a.pinned && b.pinned) return 1;
      return 0; // 可以根据需要添加其他排序规则，例如日期
    });

    setAllChats(updatedChats);
    const filteredChats = updatedChats.filter(chat =>
      chat.title.toLowerCase().includes(chatName.toLowerCase())
    );
    setChatList(filteredChats);
  };

  const PinIcon = (props: React.SVGProps<SVGSVGElement>) => (
    <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...props}>
        <path d="M12 17.5l-3.5-3.5" />
        <path d="M12 3v14.5" />
        <path d="m8.5 14l-4-4" />
        <path d="m19.5 6.5l-5-5" />
        <path d="M12 3h4.5a2.5 2.5 0 0 1 2.5 2.5V10" />
        <path d="M8.5 14H4a1 1 0 0 0-1 1v3.5a1.5 1.5 0 0 0 1.5 1.5h1" />
    </svg>
  );

  const MenuIcon = (props: React.SVGProps<SVGSVGElement>) => (
    <svg xmlns="http://www.w3.org/2000/svg" width="1.5em" height="1.5em" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...props}>
        <line x1="3" y1="12" x2="21" y2="12" />
        <line x1="3" y1="6" x2="21" y2="6" />
        <line x1="3" y1="18" x2="21" y2="18" />
    </svg>
  );

  let chatsForSelect = [...allChats];
  let activeChat = allChats.find(c => c.chat_id === chatId);
  if (!activeChat && newChatItem) {
    activeChat = {
        ...newChatItem,
        chat_id: chatId,
        title: tmpChatTitle || "新对话"
    };
  }

  const handleConfirmTitleEdit = () => {
    if (activeChat) {
      editConfirm(activeChat);
    }
    setIsEditingTitle(false);
  };

  return (
    <div className="chat-page">
      <div className="flex">
        {/* 侧边栏 */}
        <aside className={`aside ${isAsideCollapsed ? 'collapsed' : ''}`}>
          <div className="aside-content">
            <div className="media-page">
              {/* AI头像和名称展示区域 */}
              <div className="ai-info">
                <Image 
                  src={'/images/AI.png'} 
                  alt={roles.find(role => role.id === roleId)?.name || 'AI助手'} 
                  width={48} 
                  height={48} 
                  className="ai-avatar" 
                />
                <div className="ai-name">
                  {roles.find(role => role.id === roleId)?.name || 'AI助手'}
                </div>
              </div>

              <button 
                onClick={_newChat} 
                className="newChat"
              >
                <PlusIcon className="mr-1" />
                新建对话
              </button>

              <div className="search-box">
                <div className="search-input-container">
                  <SearchIcon className="search-icon" />
                  <input 
                    value={chatName} 
                    onChange={(e) => setChatName(e.target.value)}
                    onKeyDown={searchChat}
                    placeholder="搜索会话" 
                    className="search-input" 
                  />
                </div>
              </div>
              
              <div className="chat-list-container" style={{height: `${leftBoxHeight}px`}}>
                <div className="content">
                  {chatList.map((chat) => (
                    <div
                      key={chat.chat_id}
                      className={`chat-list-item ${chat.chat_id === chatId ? 'active' : ''}`}
                      onClick={() => loadChat(chat)}
                    >
                      <Image src={'/images/AI.png'} alt="ai-avatar" width={40} height={40} className="avatar" />
                      
                      <div className="chat-info">
                        {chat.edit ? (
                          <span className="chat-title-input">
                            <input
                              value={tmpChatTitle}
                              onChange={(e) => setTmpChatTitle(e.target.value)}
                              onKeyDown={(e) => titleKeydown(e, chat)}
                              id={`chat-${chat.chat_id}`}
                              onBlur={() => editConfirm(chat)}
                              onClick={stopPropagation}
                              placeholder="请输入标题"
                              className="chat-title-input-field"
                            />
                          </span>
                        ) : (
                          <span className="chat-title">{chat.title}</span>
                        )}
                      </div>

                      <span className="chat-opt">
                        <div className="dropdown">
                          <span className="dropdown-trigger" onClick={stopPropagation}>
                            <MoreIcon className="icon" />
                          </span>
                          <div className="dropdown-menu">
                            <div className="dropdown-item" onClick={() => editChatTitle(chat)}>
                              <EditIcon className="icon" /> 重命名
                            </div>
                            <div className="dropdown-item" onClick={() => pinChat(chat)}>
                               <PinIcon className="icon" /> {chat.pinned ? '取消置顶' : '置顶'}
                            </div>
                            <div className="dropdown-item delete" onClick={() => removeChat(chat)}>
                              <DeleteIcon className="icon" /> 删除
                            </div>
                          </div>
                        </div>
                      </span>
                    </div>
                  ))}
                </div>
              </div>
            </div>

            <div className="tool-box">
              <button onClick={clearAllChats} className="clear-btn">
                清除所有对话
              </button>
            </div>
          </div>
        </aside>

        {/* 主内容区 */}
        <main className={`main-content ${isAsideCollapsed ? 'aside-collapsed' : ''}`}>
          <div className="chat-config">
            <button onClick={() => setIsAsideCollapsed(!isAsideCollapsed)} className="aside-toggle">
                <MenuIcon />
            </button>
            {isAsideCollapsed ? (
                <div className="collapsed-header">
                    <Image src={activeChat?.icon || '/images/AI.png'} alt="ai-avatar" width={24} height={24} className="avatar" />
                    <span className="separator">/</span>
                    {isEditingTitle && activeChat ? (
                        <input
                            className="header-title-input"
                            value={tmpChatTitle}
                            onChange={(e) => setTmpChatTitle(e.target.value)}
                            onKeyDown={(e) => {
                                if (e.key === 'Enter') {
                                    handleConfirmTitleEdit();
                                } else if (e.key === 'Escape') {
                                    setIsEditingTitle(false);
                                }
                            }}
                            onBlur={handleConfirmTitleEdit}
                            autoFocus
                        />
                    ) : (
                        <>
                            <div className="title-dropdown-container" onMouseLeave={() => setIsHeaderMenuOpen(false)}>
                                <span className="header-title-text" onClick={() => setIsHeaderMenuOpen(!isHeaderMenuOpen)}>
                                    {activeChat?.title || "新对话"}
                                </span>
                                {isHeaderMenuOpen && activeChat && (
                                    <div className="header-dropdown-menu">
                                        <div className="dropdown-item" onClick={() => { pinChat(activeChat); setIsHeaderMenuOpen(false); }}>
                                            <PinIcon className="icon" /> {activeChat.pinned ? '取消置顶' : '置顶'}
                                        </div>
                                        <div className="dropdown-item" onClick={() => {
                                            setIsEditingTitle(true);
                                            setTmpChatTitle(activeChat.title || '');
                                            setIsHeaderMenuOpen(false);
                                        }}>
                                            <EditIcon className="icon" /> 重命名
                                        </div>
                                        <div className="dropdown-item delete" onClick={() => { removeChat(activeChat); setIsHeaderMenuOpen(false); }}>
                                            <DeleteIcon className="icon" /> 删除
                                        </div>
                                    </div>
                                )}
                            </div>
                            <button className="edit-chat-title-btn" onClick={() => {
                                if (activeChat) {
                                    setIsEditingTitle(true);
                                    setTmpChatTitle(activeChat.title || '');
                                }
                            }}>
                                <EditIcon className="icon" />
                            </button>
                        </>
                    )}
                </div>
            ) : (
                <>
                    <div className="role-model-select">
                        <select 
                            value={roleId} 
                            onChange={(e) => setRoleId(parseInt(e.target.value))}
                            className="role-select"
                        >
                            {roles.map(role => (
                            <option key={role.id} value={role.id}>{role.name}</option>
                            ))}
                        </select>

                        <select 
                            value={modelID} 
                            onChange={(e) => setModelID(parseInt(e.target.value))}
                            disabled={disableModel}
                            className="model-select"
                        >
                            {models.map(model => (
                            <option key={model.id} value={model.id}>
                                {model.name} ({model.power}算力)
                            </option>
                            ))}
                        </select>
                    </div>

                    <div className="settings">
                        <button className="setting-btn" title="插件增强">
                            <PlugIcon className="icon" />
                        </button>
                        <button onClick={() => setShowChatSetting(true)} className="setting-btn" title="设置">
                            <SettingsIcon className="icon" />
                        </button>
                    </div>
                </>
            )}
          </div>

          <div className="chat-container" style={{ height: `${mainWinHeight}px` }}>
            <div id="chat-box" className="chat-box" style={{ height: `${chatBoxHeight}px` }}>
              {showHello ? (
                <Welcome onSend={autofillPrompt} />
              ) : (
                chatData.map(item => (
                  item.type === 'prompt' ? (
                    <ChatPrompt key={item.id} data={item} {...{ listStyle }} />
                  ) : (
                    <ChatReply 
                      key={item.id} 
                      data={item} 
                      onRegen={reGenerate} 
                      readOnly={false} 
                      {...{ listStyle }}
                    />
                  )
                ))
              )}

              <BackTop target="#chat-box" right={30} bottom={155} />
            </div>

            <div className="input-box">
              <div className="input-box-inner">
                <div className="input-body">
                  <div ref={textHeightRef} className="hide-div">{prompt}</div>
                  <div className="input-border">
                    <div className="input-inner">
                      {files.length > 0 && (
                        <div className="file-list">
                          <FileList files={files} onRemoveFile={removeFile} />
                        </div>
                      )}
                      <textarea
                        ref={inputRef}
                        className="prompt-input"
                        rows={row}
                        value={prompt}
                        onChange={(e) => setPrompt(e.target.value)}
                        onKeyDown={onInput}
                        placeholder="请输入您的问题..."
                        autoFocus
                      />
                    </div>
                    <div className="flex-between">
                      <div className="flex little-btns" style={{width:'1%'}}>
                        {/* <button className="tool-item-btn" onClick={realtimeChat} title={`实时语音对话，每次消耗${config.advance_voice_power}算力`}>
                          <MicIcon className="icon" />
                        </button> */}

                        <FileSelect onSelected={insertFile} />
                      </div>
                      <div className="flex little-btns">
                        {showStopGenerate ? (
                            <button onClick={stopGenerate} className="stop-btn">
                              <PauseIcon className="icon" />
                            </button>
                        ) : (
                            <button onClick={() => sendMessage()} className="send-btn">
                              <SendIcon className="icon" />
                            </button>
                        )}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </main>
      </div>

      {/* 对话框 */}
      {showNotice && (
        <div className="notice-dialog">
          <div className="notice-dialog-header">
            <h2>网站公告</h2>
            <button onClick={() => setShowNotice(false)} className="close-btn">×</button>
          </div>
          <div className="notice-dialog-body">
            <div dangerouslySetInnerHTML={{ __html: notice }} />
          </div>
          <div className="notice-dialog-footer">
            <button onClick={notShow} className="primary-btn">我知道了，不再显示</button>
          </div>
        </div>
      )}

      {showChatSetting && (
        <ChatSetting show={showChatSetting} onHide={() => setShowChatSetting(false)} />
      )}

      {showConversationDialog && (
        <div className="conversation-dialog">
          <div className="conversation-dialog-header">
            <h2>实时语音通话</h2>
            <button onClick={() => setShowConversationDialog(false)} className="close-btn">×</button>
          </div>
          <div className="conversation-dialog-body">
            {!frameLoaded && <div className="loading">加载中...</div>}
            <iframe
              style={{ width: '100%', height: 'calc(100vh - 100px)', border: 'none' }}
              src={voiceChatUrl}
              onLoad={() => setFrameLoaded(true)}
              allow="microphone *;camera *;"
            />
          </div>
        </div>
      )}
    </div>
  );
}